import React, { useState, useEffect, useMemo, useRef } from "react";
import * as echarts from "echarts";
export default () => {
  const ref = useRef();
  const [chart, setChart] = useState(null);
  const [data, setData] = useState(null);
  const option = useMemo(() => {
    if (!data) return null;
    let op = {
      xAxis: {
        type: "category",
        boundaryGap: false,
        axisLine: {
          show: false,
          onZero: true,
        },
        axisTick: { show: false },
        data: ["3:00", "4:00", "5:00", "6:00", "7:00", "8:00", "9:00"],
      },
      yAxis: {
        type: "value",
        splitNumber: 3,
        splitLine: {
          lineStyle: {
            type: "dashed",
          },
        },
      },
      // tooltip: {
      //   trigger: "item",
      //   // formatter:'人数占比:<br/>{b}: {d}%',
      // },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          label: {
            backgroundColor: "#6a7985",
          },
        },
      },
      grid: {
        // left: "0%",
        // right: "0%",
        top: "3%",
        left: "3%",
        right: "8%",
        bottom: "3%",
        containLabel: true,
      },
      series: [
        {
          data: [820, 932, 901, 934, 1290, 1330, 1320],
          type: "line",
          smooth: true,
          lineStyle: {
            color: "rgba(12, 180, 231, 1)",
            width: 1,
          },
          areaStyle: {
            color: "rgba(24, 185, 234, 0.11)",
          },
          // itemStyle: {
          //   borderWidth: 0,
          //   borderType: "dotted",
          // },
        },
      ],
    };
    return op;
  }, [data]);

  /*=======请求数据 =======*/
  const getData = () => {
    let lst = [{ name: "抖音" }, { name: "微信" }, { name: "微博" }, { name: "小红书" }];
    for (let i = 0; i < lst.length; i++) {
      lst[i].value = Math.round(Math.random() * 2000);
    }
    setData(lst);
  };

  /* ======== 定时改变data ======= */
  useEffect(() => {
    getData();
    let timer = setInterval(() => {
      getData();
    }, 3000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  /* ======== 生成图表实例 ======= */
  useEffect(() => {
    ref.current && setChart(echarts.init(ref.current));
  }, []);

  /* ======= 渲染图表 ====== */
  useEffect(() => {
    chart && option && chart.setOption(option);
  }, [chart, option]);

  return (
    <div style={{ width: "100%", height: "100%" }} ref={ref}></div>
  );
};
